<template>
	<header-page-layout ref="header" title="蓝牙连接" base-background-color="#f8f8ff" background-color="#ffffff" @headerclick="onHeaderClick">
		<template v-slot:headerleft><u-icon name="arrow-left"></u-icon></template>
		<view class="bluetooth-connection-page page-padding">
			<view v-for="(item,index) in myBluetoothes" :key="item.deviceId" class="bluetooth-btn" @tap="onConnect(item.deviceId)">
				<view class="blue-btn-id">{{item.deviceId}}</view>
				<view class="blue-btn-name">{{item.name}}</view>
			</view>
		</view>
		<template v-slot:footer>
			<view class="page-padding page-footer-padding">
				<u-button type="primary" text="重新搜索" @click="research" :disabled="myBluetoothes.length===0"></u-button>
			</view>
		</template>
	</header-page-layout>
</template>

<script>
import HeaderPageLayout from '@/components/HeaderPageLayout.vue'
import BluePrint from './bluePrint.js'
export default {
	name:'bluetoothPrintConnectionPage',
	components:{HeaderPageLayout},
	data(){
		return {
			initAgain:false,
			myBluetoothes:[]
		}
	},
	methods:{
		onHeaderClick(type){
			if (type==='left') {
				uni.redirectTo({url:this.$config.path.login})
			}
		},
		search(re=false){
			let methodName = 'getBlueToothes'
			if (re) methodName = 'reGetBlueToothes'
			BluePrint[methodName](this.$store).then((res)=>{
				this.myBluetoothes = res
			}).catch((err)=>{
				if (typeof err !== 'string'){
					err = '获取蓝牙设备列表失败'
				}
				BluePrint.alert(err)
			})
		},
		research(){
			this.myBluetoothes = [];
			this.search(true)
		},
		onConnect(id){
			BluePrint.connect(this.$store,id).then(()=>{
				uni.navigateBack()
			}).catch((err)=>{
				if (typeof err !== 'string'){
					err = '连接蓝牙设备失败'
				}
				BluePrint.alert(err)
			})
		}
	},
	onLoad(option) {
		if (option.again==='1') {
			this.initAgain = true
		} else {
			this.initAgain = false
		}
	},
	onReady() {
		this.search(this.initAgain)
	}
}
</script>

<style lang="scss" scoped>
.header-icon-btn{
	font-size: 1.3rem;
}
.page-padding{
	padding: 0 30rpx;
}
.page-footer-padding{
	padding-top: 20rpx;
	padding-bottom: 20rpx;
}
.bluetooth-connection-page{
	padding-top: 30rpx;
	.bluetooth-btn{
		box-sizing: border-box;
		width: 100%;
		margin-bottom: 30rpx;
		border: 1px solid #F18201;
		background-color: #f8c07f;
		color: #fff;
		border-radius: 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
		font-size: 30rpx;
		.blue-btn-id,.blue-btn-name{
			word-wrap: break-word;
			word-break: break-all;
			white-space: pre-wrap;
			text-align: center;
		}
		.blue-btn-name{
			font-size: 1.5em;
			font-weight: bold;
		}
		&:last-child{
			margin-bottom: 0;
		}
	}
}
</style>